
import com.alibaba.fastjson.JSONObject;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

/**
 * @author xienian
 * @description
 * @date 2024/12/17 11:12
 */

public class HttpUtils {

    private static final String PATH = "path"; //入参key
    public static final String OCR = "http://localhost:5000/ocr"; //文字识别
    public static final String TABLE_OCR = "http://localhost:5000/table_ocr"; //表格识别
    public static final String TABLE_LIST_OCR = "http://localhost:5000/table_list_ocr"; //表格识别

    /**
     *
     * @param url
     * @param path
     * @return 调用识别接口
     * @throws UnsupportedEncodingException
     */
    public static String rec(String url, String path) throws IOException {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put(PATH, path);
        StringEntity entity = new StringEntity(jsonObject.toString());
        return execute(entity,url);
    }

    private static String execute(StringEntity entity, String url) throws IOException {
        try {
            HttpPost httpPost = new HttpPost(url);
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-type", "application/json");


            httpPost.setEntity(entity);
            CloseableHttpClient client = HttpClients.createDefault();
            CloseableHttpResponse response = client.execute(httpPost);

            BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            String line;
            StringBuilder result = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                result.append(line).append("\n");
            }

            response.close();
            client.close();
            return result.toString();
        } catch (Exception e) {
            throw new IOException("识别失败,请检查文件内容是否正常");
        }
    }

    public static void main(String[] args) throws IOException {
        //调用示例
        String rec = rec(OCR, "D:\\1.jpg");
        System.out.println(rec);
    }
}
